import React, { Component } from 'react'
import MyNavBar from 'components/navbar';
import styles from './index.less'
import { Icon, InputItem, List, Button, Modal, Toast } from 'antd-mobile'
import { connect } from 'dva'
import { createForm } from 'rc-form';
import { idCardRegular, unifiedSocialID } from 'utils/regular';
import router from 'umi/router';
import success from 'static/EnterpriseCertificationInformationImg/success.png'
import fail from 'static/EnterpriseCertificationInformationImg/fail.png'
import loading from 'static/EnterpriseCertificationInformationImg/loading.png'

import { getIsDingTalk } from 'utils/utils';
import commonStyles from 'utils/common.less';
import { PROCESS_STATUS } from 'utils/Enum'
/**
 * @description 用于企业认证填写信息的页面
 * @author 马羽
 * @date 2019-12-26
 * @class EnterpriseCertificationInformation
 * @extends {Component}
 */

//测试实验wsid
//const userWsid = 'WSID_EUSR_0000016f54d57d0e00d861ab73a30001'

const alert = Modal.alert;

@connect(({ pdfModel, EnterpriseCertificationInformationModel }) => ({ pdfModel, EnterpriseCertificationInformationModel }))
class EnterpriseCertificationInformation extends Component {
	state = {
		errorIDCard: false,  //身份证号码是否错误
		imgModal: false,  //图片预览的对话框
		showAns: null,  //显示提交信息后的结果
		disable: true, //btn是否可以按
		userWsid: ''  //用户的wsid
	}
	msg = '证件必须完整清晰且在有效期内，大小不超过5M'
	info = '(请上传三证合一的营业执照)'
	maxSize = 5 * 1024 * 1024
	//进入页面就去获取企业信息，查看是否已经上传企业营业执照
	componentDidMount() {
		let userWsid = localStorage.getItem('userWsid')
		this.setState({
			userWsid
		})
		let { dispatch, EnterpriseCertificationInformationModel: { imgUrl } } = this.props
		//如果没有上传图片，就去请求图片
		if (!imgUrl) {
			Toast.loading('加载中', 0)
			dispatch({
				type: 'EnterpriseCertificationInformationModel/getBusinessInfo',
				payload: {
					userWsid
				},
				callback: (state, msg) => {
					if (state === 'success') {
						Toast.hide();
					} else {
						Toast.fail(msg, 2, null, false)
					}
					const { form: { validateFields } } = this.props
					let that = this
					validateFields((err, val) => {
						let { EnterpriseCertificationInformationModel: { imgUrl } } = this.props
						if (err || !imgUrl) {
							that.setState({
								disable: false
							})
						} else {
							that.setState({
								disable: true
							})
						}
					})

				}
			})
		}

	}
	render() {
		const isDingTalk = getIsDingTalk()
		let { errorIDCard, imgModal, showAns, disable } = this.state
		let { imgUrl, agent, defaultImgUrl, name, regNum, legalName, legalIDCard } = this.props.EnterpriseCertificationInformationModel
		const { getFieldDecorator } = this.props.form;

		// const contentContainer=commonStyles.headerTop
		const contentContainer = isDingTalk === 'true' ? '' : commonStyles.headerTop
		return (
			<div className={styles.baseLayout}>
				{
					showAns === null ?
						null
						:
						<div className={styles.showAns}>
							{
								showAns === 'success' ?
									<img src={success}></img>
									:
									<img src={showAns === 'error' ? fail : loading}></img>
							}
						</div>
				}
				{
					imgModal ?
						<div className={styles.imgModalWrapper} onClick={this.showHideImgModal}>
							<img className={styles.showModalImg} src={imgUrl ? imgUrl : defaultImgUrl}></img>
						</div>
						:
						null
				}
				<MyNavBar title="企业认证" backUrl={`/EnterpriseCertificationListBackUps`} />
				{isDingTalk === 'true' ? '' : <div style={{ height: '7vh' }}></div>}
				<div className={styles.content} style={{ height: isDingTalk === 'true' ? '90vh' : '82vh' }}>
					<div className={styles.imgWrapper}>
						<div className={styles.BusinessLicenseWrapper} onClick={e => this.showHideImgModal(e)}>
							<img className={styles.BusinessLicense} src={imgUrl ? imgUrl : defaultImgUrl} />
							<div className={styles.searchIconWrapper}>
								<Icon className={styles.searchIcon} type="search" size={'xxs'} />
							</div>
						</div>
						<div className={styles.msg}>
							<div>{this.msg}</div>
							<div>{this.info}</div>
						</div>
						<div className={styles.uploadImgWrapper}>
							<button className={styles.uploadImgBtn}>
								{
									imgUrl ?
										'重新上传/拍照'
										:
										'拍照/上传图片'
								}
								<input type="file" onChange={e => this.uploadImg(e)} className={styles.upLoadImgInput} />
							</button>
						</div>
					</div>
					<div onClick={this.switch} className={styles.switchWrapper}>
						切换申请人身份
                  	<Icon className={styles.turnRight} type="right" />
					</div>
					<form className={styles.infoForm}>
						<List className={styles.formList}>
							{getFieldDecorator('enterpriseAuthType', {
								initialValue: agent === 'LEGAL_PERSON_AUTH' ? '法定代表' : '经办人',
								rules: [
									{
										required: false,
										message: '申请人身份',
									},
								],
							})(
								<InputItem editable={false} clear placeholder={agent === 'LEGAL_PERSON_AUTH' ? '法定代表' : '经办人'}>
									申请人身份
                      			</InputItem>
							)}
							{getFieldDecorator('enterpriseName', {
								initialValue: name || "",
								rules: [
									{
										required: true,
										message: '请输入企业名称',
									},
								],
							})(
								<InputItem clear placeholder="填写证件上一致的名称">
									企业名称
                      			</InputItem>
							)}
							{getFieldDecorator('unifiedSocialID', {
								initialValue: regNum || "",
								rules: [
									{
										required: true,
										message: '请输入统一信用代码',
									},
									{
										pattern: unifiedSocialID.reg,
										message: '请输入18位统一信用代码'
									}
								],
							})(
								<InputItem clear placeholder="填写证件上一致的号码">
									统一信用代码
                      			</InputItem>
							)}
							{
								getFieldDecorator('legalName', {
									initialValue: legalName || "",
									rules: [{
										required: true,
										message: '请输入法人姓名'
									}]
								})(
									<InputItem
										clear
										editable={agent === 'LEGAL_PERSON_AUTH' ? false : true}
										placeholder={agent === 'LEGAL_PERSON_AUTH' ? legalName : '填写代表姓名'}
									>
										法人姓名
                        			</InputItem>
								)
							}
							{getFieldDecorator('legalIdCardNo', {
								initialValue: legalIDCard || "",
								rules: [
									{
										required: true,
										message: '请输入法人身份证号'
									},
									{
										pattern: idCardRegular.reg,
										message: '身份证号码格式错误'
                                    }
								],
							})(
								<InputItem
									editable={agent === 'LEGAL_PERSON_AUTH' ? false : true}
									className={styles.inputItem}
									clear
									placeholder={agent === 'LEGAL_PERSON_AUTH' ? legalIDCard : "填写身份证号"}
									onChange={this.InputIDChange}
								>
									法人身份证号
                      			</InputItem>
							)}
							{
								errorIDCard &&
								<div className={styles.errorMsg}>
									身份证号填写错误
                      			</div>
							}
						</List>
					</form>

				</div>
				{/*<div style={{height:'1.4rem'}}></div>*/}
				<div className={styles.footerContainer}>
					<Button onClick={e => this.submit(e)} type="primary">
						下一步
                	</Button>
				</div>

			</div>
		)
	}

	//检查输入是否正确
	checkIsRight = e => {
		let { EnterpriseCertificationInformationModel: { imgUrl } } = this.props
		const { form: { validateFields } } = this.props
		let errMsg = ''
		validateFields((err, val) => {
			for(let i in err) {
				if(!errMsg) {
					errMsg =  err[i].errors[0].message
				}
			}
		})
		if(!imgUrl) errMsg = '请上传营业执照'
		return errMsg
	}

	showModel = (msg, fn = () => {}) => {
		alert('', msg, [{
			text: '确认',
			onPress: fn,
			style: {
				color: 'rgba(0, 137, 255, 1)'
			}
		}])
	}

	//上传图片
	uploadImg(e) {
		let file = e.currentTarget.files[0] || ''
		//如果点击的是确定按钮
		if (file) {
			let { type } = file
			let reg = new RegExp('image/jpeg$|image/jpg$|image/png$', 'i')
			//如果是图片类型
			if (reg.test(type)) {
				let { size } = file
				//如果图片大于5MB
				if (size > this.maxSize) {
					Toast.fail('图片太大,请更换图片', 2, null, false)
					return
				}
				let { userWsid } = this.state
				let { dispatch, EnterpriseCertificationInformationModel: { idttyWsid } } = this.props
				let fd = new FormData()
				fd.append('file', file)
				Toast.loading('上传图片中', 0)
				dispatch({
					type: 'EnterpriseCertificationInformationModel/upLoadImg',
					payload: {
						file: fd,
						userWsid,  //测试sid
						idttyWsid
					},
					callback: (status, msg) => {
						if (status === 'error') {
							Toast.fail(msg, 2, null, false)
						} else {
							let { form: { setFieldsValue }, EnterpriseCertificationInformationModel: { name, regNum } } = this.props
							if (name || name.length != 0) {
								setFieldsValue({
									enterpriseName: name,
								})
							}
							if (regNum || regNum.length != 0) {
								setFieldsValue({
									unifiedSocialID: regNum
								})
							}

							Toast.hide()
							// Toast.success(msg,2,null,false)
						}
					}
				})
			} else {
				Toast.fail('请上传jpg,png,jpeg格式文件', 2, null, false)
			}
		}
	}

	//身份证输入框发生改变验证输入的格式
	InputIDChange = (e) => {
		//如果身份证格式不对并且不为空
		if (!idCardRegular.reg.test(e) && e !== '') {
			this.setState({
				errorIDCard: true
			})
		} else {
			this.setState({
				errorIDCard: false
			})
		}
	}

	//修改代理人
	switch = async e => {
		let { form: { setFieldsValue } } = this.props
		let { dispatch, EnterpriseCertificationInformationModel: { agent, legalName, legalIDCard } } = this.props
		let { errorIDCard } = this.state
		if (agent !== 'LEGAL_PERSON_AUTH') {
			//如果当前是经办人代表人,表示即将切换为法人代表人
			//就清除
			setFieldsValue({
				legalIdCardNo: legalIDCard,
				legalName,
				enterpriseAuthType: '法人代表'
			})
			if (errorIDCard) {
				this.setState({
					errorIDCard: false
				})
			}
		} else {
			setFieldsValue({
				legalIdCardNo: '',
				legalName: '',
				enterpriseAuthType: '经办人'
			})
			if (errorIDCard) {
				this.setState({
					errorIDCard: false
				})
			}
		}
		let { userWsid } = this.state
		await dispatch({
			type: 'EnterpriseCertificationInformationModel/switchAgent',
			payload: {
				userWsid
			}
		})
	}

	//点击下一步
	submit = e => {
		let status = this.checkIsRight()
		if(status) {
			this.showModel(status)
			return
		}
		const { form: { validateFields } } = this.props
		let { imgUrl, registerName } = this.props.EnterpriseCertificationInformationModel
		let { errorIDCard } = this.state
		let that = this
		
		validateFields((err, val) => {
			//如果信息不完整或者身份证格式错误
			alert('', '请确保提交的信息正确，一旦发生错误，你将重新填写，将会耽误您认证的时间', [
				{
					text: '修改资料',
					onPress: () => {
						return false
					},
					style: {
						color: 'rgba(0, 137, 255, 1)'
					}
				},
				{
					text: '确认无误',
					onPress: () => {
						//如果点击的确认无误
						let { userWsid } = this.state
						let { dispatch, EnterpriseCertificationInformationModel: { agent } } = this.props
						//认证人身份
						val.enterpriseAuthType = agent
						//企业用户wisd
						val.eUserWsid = userWsid
						//身份证类型 二代居民身份证
						val.legalIdCardType = 'SECOND_GENERATION_IDCARD'
						//开始发起请求
						that.setState({
							showAns: 'loading'
						})
						dispatch({
							type: 'EnterpriseCertificationInformationModel/submit',
							payload: { ...val },
							callback: (state, msg) => {
								if (state === 'normal') {
									let { identity: { status, description } } = msg
									if (status === 'PRIMARY_PASSED') {
										//验证通过
										that.setState({
											showAns: 'success'
										}, () => {
											setTimeout(function () {
												router.push({
													pathname: '/EnterpriseCertificationResult',
													query: {
														status: PROCESS_STATUS.EUSR_AUTHORIZING_SUCCESS
													}
												})
											}, 2000)
										})
									} else {
										//验证不通过
										that.setState({
											showAns: 'error'
										}, () => {
											setTimeout(function () {
												router.push({
													pathname: '/EnterpriseCertificationResult',
													query: {
														status: PROCESS_STATUS.EPUSR_AUTHORIZING_ERROR,
														msg: description
													}
												})
											}, 2000)
										})
									}

								} else {
									//异常
									that.setState({
										showAns: 'error'
									}, () => {
										setTimeout(function () {
											router.push({
												pathname: '/EnterpriseCertificationResult',
												query: {
													status: 'error',
													msg: msg
												}
											})
										}, 2000)
									})
								}
							}
						})
					},
					style: {
						color: 'rgba(0, 137, 255, 1)',
						fontWeight: '600'
					}
				}
			])
		})
	}

	//显示或者隐藏图片预览
	showHideImgModal = e => {
		this.setState(prveState => ({
			imgModal: !prveState.imgModal
		}))
	}
}

export default createForm()(EnterpriseCertificationInformation)
